<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Bulk Email Sender</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="../css/wangeditor.css" />
    <link rel="stylesheet" href="../css/element.css" />
    <link rel="stylesheet" href="../css/index.css" />
    <script src="../js/vue.js"></script>
    <script src="../js/axios.js"></script>
    <script src="../js/element.js"></script>
    <script src="../router.js"></script>
    <style>
        body {
            background-color: #f0f2f5;
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 40px;
        }

        .container {
            max-width: 880px;
            margin: auto;
            background: #fff;
            padding: 30px 40px;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        h2 {
            margin-bottom: 24px;
            font-size: 24px;
            color: #333;
        }

        label {
            display: block;
            margin-top: 20px;
            font-weight: bold;
            font-size: 15px;
            color: #444;
        }

        input,
        textarea {
            width: 100%;
            padding: 10px 14px;
            margin-top: 6px;
            font-size: 15px;
            border-radius: 6px;
            border: 1px solid #ccc;
            box-sizing: border-box;
        }

        #recipients {
            min-height: 80px;
        }

        .editor-container {
            border: 1px solid #ccc;
            border-radius: 6px;
            overflow: hidden;
            margin-top: 10px;
        }

        .editor-toolbar,
        .editor-body {
            padding: 10px;
        }

        button {
            margin-top: 30px;
            padding: 12px 30px;
            background-color: #409eff;
            color: #fff;
            font-size: 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #2a78d4;
        }

        .error {
            color: rgb(219, 128, 128);
            font-size: 12px;
            margin-top: 5px;
        }

        #output {
            margin-top: 30px;
            white-space: pre-wrap;
            background: #f9f9f9;
            padding: 20px;
            border: 1px dashed #ccc;
        }

        [data-menu-key="group-image"] {
            display: none !important;
        }

        [data-menu-key="group-video"] {
            display: none !important;
        }
    </style>
</head>

<body>
    <div class="container" id="app">
        <label for="recipients">收件人（多个用逗号分隔）</label>
        <textarea id="recipients" placeholder="例如：a@example.com, b@example.com"></textarea>
        <div class="error" id="recipientsError"></div>

        <label for="subject">主题</label>
        <input type="text" id="subject" placeholder="请输入邮件主题" />
        <div class="error" id="subjectError"></div>

        <label>内容</label>
        <div class="editor-container">
            <div id="toolbar" class="editor-toolbar"></div>
            <div id="editor" class="editor-body" style="height: 300px;"></div>
        </div>
        <div class="error" id="contentError"></div>

        <button id="sendBtn" onclick="sendEmail()">发送邮件</button>

        <div id="output"></div>
    </div>

    <!-- wangEditor 脚本 -->
    <script src="../js/wangeditor.js"></script>
    <script>
        const tokens = JSON.parse(storage.get(loginKey))

        window.onload = async () => {
            try {
                const response = await axios.get(api + '/queryEmail',{
                    headers: {
                        Authorization: `Bearer ${tokens.token}` // 或者其他格式，比如 'token': yourToken
                    }
                });
                if (response.data.code === 200 && Array.isArray(response.data.data)) {
                    const emailsStr = response.data.data.join(', ');
                    document.getElementById('recipients').value = emailsStr;
                } else {
                    console.warn('接口返回数据异常:', response.data);
                }
            } catch (error) {
                console.error('请求邮箱列表失败:', error);
            }
        };




        const { createEditor, createToolbar } = window.wangEditor;

        // 初始化编辑器
        const editor = createEditor({
            selector: '#editor',
            html: '',
            config: {
                placeholder: '请输入邮件内容...',
            },
            mode: 'default',
        });

        createToolbar({
            editor,
            selector: '#toolbar',
            mode: 'default',
        });

        function validateEmail(email) {
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
        }


        async function sendEmail() {
            const recipientsRaw = document.getElementById('recipients').value;
            const subject = document.getElementById('subject').value.trim();
            const content = editor.getHtml().trim();

            const recipients = recipientsRaw.split(',').map(r => r.trim()).filter(r => r);

            // 清除错误提示和输出
            document.getElementById('recipientsError').innerText = '';
            document.getElementById('subjectError').innerText = '';
            document.getElementById('contentError').innerText = '';
            document.getElementById('output').innerText = '';

            // 校验
            let hasError = false;

            if (recipients.length === 0) {
                document.getElementById('recipientsError').innerText = '请输入至少一个邮箱地址';
                hasError = true;
            } else {
                const invalid = recipients.find(r => !validateEmail(r));
                if (invalid) {
                    document.getElementById('recipientsError').innerText = `无效的邮箱地址: ${invalid}`;
                    hasError = true;
                }
            }

            if (!subject) {
                document.getElementById('subjectError').innerText = '请输入邮件主题';
                hasError = true;
            }

            if (!content || content === '<p><br></p>') {
                document.getElementById('contentError').innerText = '邮件内容不能为空';
                hasError = true;
            }

            if (hasError) return;

            // 禁用按钮避免重复点击
            const sendBtn = document.getElementById('sendBtn');
            sendBtn.disabled = true;
            sendBtn.innerText = '发送中...';

            try {
                const response = await axios.post(`${api}/massEmail`, {
                    recipients: recipients.join(','), // 逗号分隔字符串
                    subject,
                    html: content,
                }, {
                    headers: {
                        Authorization: `Bearer ${tokens.token}` // 或者其他格式，比如 'token': yourToken
                    }
                });

                if (response.data.success) {
                    ELEMENT.Message({
                        message: `✅ 邮件发送成功！成功数量：${response.data.successCount}，失败数量：${response.data.failedCount}`,
                        type: 'success',
                        duration: 3000,
                    });
                    document.getElementById('output').innerText = `收件人：${recipients.join(', ')}
主题：${subject}

内容（HTML）：
${content}`;
                } else {
                    ELEMENT.Message({
                        message: `❌ 邮件发送失败: ${response.data.message}`,
                        type: 'error',
                        duration: 3000,
                    });
                    document.getElementById('output').innerText = `错误信息：${response.data.message}`;
                    errorLog('email-sender-password', response.data.message)
                }
            } catch (error) {
                ELEMENT.Message({
                    message: `❌ 请求出错: ${error.message}`,
                    type: 'error',
                    duration: 3000,
                });
                document.getElementById('output').innerText = `请求出错：${error.message}`;
                errorLog('email-sender-password', error.message)
            } finally {
                sendBtn.disabled = false;
                sendBtn.innerText = '发送邮件';
            }
        }
    </script>
</body>

</html>